using System;
using System.Collections;
using System.Collections.Specialized;
using System.Data;
using Sedna.Core.Common;
using Sedna.Core.Common.Objects.Navigation;

namespace Sedna.Core.Controller.Configurations
{
	public class IdColumnBasedDataGridLineSelector : IDataGridLineSelector
	{
        private IScopePathParser scopePathParser;
        private IDataGridCommandArgumentsParser commandArgumentsParser;

	    public IScopePathParser ScopePathParser
	    {
	        set { scopePathParser = value; }
	    }

	    public IDataGridCommandArgumentsParser CommandArgumentsParser
	    {
	        set { commandArgumentsParser = value; }
	    }

	    private string idField = "ID";

		public string IdField
		{
			set { idField = value; }
		}

		public bool CheckIfSelected(object dataRow, IExecutionContext executionContext)
		{
			string lineSelection = (string)executionContext.GetFromCurrentScope("LineSelection");
			if(lineSelection == null || string.Empty == lineSelection)
			{
				return false;
			}


            IDictionary parameters = commandArgumentsParser.ParseCommandArguments(lineSelection);
			if(parameters == null)
			{
				return false;
			}
			string paramValue = (string)parameters[idField];
			if(paramValue == null || string.Empty == paramValue)
			{
				return false;
			}
		    
		    object rowValue = GetRowValue(dataRow);
		    if (rowValue==null) return false;
            return paramValue.Equals(rowValue.ToString());
		}
	    
	    private object GetRowValue(object dataRow)
	    {
	        
			DataRowView drv = dataRow as DataRowView;
	        if (drv!=null)
	        {
	            return drv[idField];
	        }
            return scopePathParser.Parse(dataRow, idField).Value;
	    }
	}
}
